package com.apache.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>@Description http请求帮助类
 * <p>@Copyright(c)2013:
 * <p>@Author: lvcai
 * <p>@Create Date 2013-7-29 下午03:54:28
 * <p>@Modified By:lvcai
 * <p>@Modified Date:2013-7-29 下午03:54:28
 * <p>@version v1.0
 */
public class PostHttp {
	private static Logger logger = LoggerFactory.getLogger(PostHttp.class);

	/**
	 * 公共方法
	 * post http 请求，接受返回的结果xml文档	 
	 * @param url webservice地址
	 * @param parasInput 传递的参数
	 * @return xml类型字符串
	 */
	public static String postHttp(String url, NameValuePair[] parasInput) {
		StringBuilder sb = new StringBuilder();
		PostMethod postMethod = new PostMethod(url);
		try {
			//重新构造参数数组，是为了加入公共参数：随机数，以防缓存影响执行结果				
			NameValuePair[] paras = null;
			if (parasInput != null) {
				paras = new NameValuePair[parasInput.length + 1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
				for (int i = 0; i < parasInput.length; i++) {
					paras[i + 1] = parasInput[i];
				}
			} else {
				paras = new NameValuePair[1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
			}

			HttpClient client = new HttpClient();
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			postMethod.setRequestBody(paras);//绑定参数
			logger.info("HTTP请求发送成功");
			int statusCode = client.executeMethod(postMethod);
			logger.info("服务端返回请求状态，状态码为：" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {//如果执行成功
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
				String line = null;
				try {
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				inputStream.close();
			} else {
				logger.error("HTTP请求响应失败，错误码为：" + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();//释放连接
		}
		return sb.toString();
	}

	/**
	 * 公共方法
	 * post http 请求，接受返回的结果xml文档	 
	 * @param url webservice地址
	 * @param parasInput 传递的参数
	 * @return Document 对象
	 */
	public static Document postHttpDocument(String url, NameValuePair[] parasInput) {
		Document doc = null;
		PostMethod postMethod = new PostMethod(url);
		try {
			//重新构造参数数组，是为了加入公共参数：随机数，以防缓存影响执行结果				
			NameValuePair[] paras = null;
			if (parasInput != null) {
				paras = new NameValuePair[parasInput.length + 1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
				for (int i = 0; i < parasInput.length; i++) {
					paras[i + 1] = parasInput[i];
				}
			} else {
				paras = new NameValuePair[1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
			}

			HttpClient client = new HttpClient();
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

			postMethod.setRequestBody(paras);//绑定参数
			logger.info("HTTP请求发送成功");
			int statusCode = client.executeMethod(postMethod);
			logger.info("服务端返回请求状态，状态码为：" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {//如果执行成功
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				doc = (new SAXReader()).read(inputStream);
				inputStream.close();
			} else {
				logger.error("HTTP请求响应失败，错误码为：" + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();//释放连接
		}
		return doc;
	}

	/**
	 * 
	 * @param url
	 * @param parasInput
	 * @return
	 */
	public static String postHttpString(String url, NameValuePair[] parasInput) {
		String value = "";
		PostMethod postMethod = new PostMethod(url);
		try {
			//重新构造参数数组，是为了加入公共参数：随机数，以防缓存影响执行结果				
			NameValuePair[] paras = null;
			if (parasInput != null) {
				paras = new NameValuePair[parasInput.length + 1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
				for (int i = 0; i < parasInput.length; i++) {
					paras[i + 1] = parasInput[i];
				}
			} else {
				paras = new NameValuePair[1];
				paras[0] = new NameValuePair("httpRand", "" + new Date().getTime());
			}

			HttpClient client = new HttpClient();
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

			postMethod.setRequestBody(paras);//绑定参数
			logger.info("HTTP请求发送成功");
			int statusCode = client.executeMethod(postMethod);
			logger.info("服务端返回请求状态，状态码为：" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {//如果执行成功
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				byte[] temp = new byte[1024];
				byte[] tmp = new byte[1024 * 4];
				int t1 = 0;
				int t2 = 0;
				while ((t2 = inputStream.read(temp)) != -1) {
					System.arraycopy(temp, 0, tmp, t1, t2);
					t1 = t1 + t2;
				}
				value = new String(tmp, "UTF-8");
				value = value.trim();

				inputStream.close();
			} else {
				logger.error("HTTP请求响应失败，错误码为：" + statusCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			postMethod.releaseConnection();//释放连接
		}
		return value;
	}

}